//
//  CoreDataManager.m
//  ErJie
//
//  Created by yaorenjin on 2017/1/30.
//  Copyright © 2017年 yaorenjin. All rights reserved.
//

#import "CoreDataManager.h"
#import "AppDelegate.h"

static id _instace;

@implementation CoreDataManager
@synthesize managedObjectModel = _managedObjectModel;

+(CoreDataManager*)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _instace = [[self alloc] init];
        
        
    });
    
    return _instace;
}

-(id)init
{
    self = [super init];
    
    if (self) {
        
    }
    
    return self;
}

- (NSManagedObjectContext *)managedObjectContext
{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return appDelegate.persistentContainer.viewContext;
}

- (void)saveContext
{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate saveContext];
}

- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"ErJie" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

//转换对象
-(ShangPinModel*)toShangPinModel:(ShangPinEntity*)spEntity
{
    ShangPinModel* spModel = [[ShangPinModel alloc] init];
    spModel.chenben = spEntity.chenben;
    spModel.danjia = spEntity.danjia;
    spModel.fId = spEntity.fId;
    spModel.flName = spEntity.flName;
    spModel.kucun = spEntity.kucun;
    spModel.name = spEntity.name;
    spModel.sId = spEntity.sId;
    spModel.time = spEntity.time;
    spModel.buyCount = spEntity.buyCount;
    
    return spModel;
}

//插入客户
-(BOOL)insertKeHu:(KeHuEntity*)khEntity
{
    khEntity.time = [NSDate date];
    khEntity.kId = [[self getKid] integerValue];
    NSError* erro = nil;
    
    if (![self.managedObjectContext save:&erro]) {
        
        NSLog(@"保存失败-->>%@",erro);
        
        return NO;
        
    }
    else
    {
        return YES;
    }
}

-(KeHuEntity*)createKeHuEntity
{
    return [NSEntityDescription insertNewObjectForEntityForName:@"KeHuEntity" inManagedObjectContext:self.managedObjectContext];
}

//删除客户
-(BOOL)deleteKeHu:(KeHuEntity*)khEntity
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"KeHuEntity"];
    
    //查到到你要删除的数据库中的对象
    NSPredicate *predic = [NSPredicate predicateWithFormat:@"kId = %@",[NSString stringWithFormat:@"%lld",khEntity.kId]];
    request.predicate = predic;
    
    //请求数据
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:nil];
    
    for (KeHuEntity *kh in objs) {
        
        [self.managedObjectContext deleteObject:kh];
    }
    
    if ([self.managedObjectContext save:nil]) {
        
        return YES;
    }
    else
    {
        return NO;
    }
}

//更新客户
-(BOOL)updateKeHu:(KeHuEntity*)khEntity
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"KeHuEntity"];
    //查到到你要删除的数据库中的对象
    NSPredicate *predic = [NSPredicate predicateWithFormat:@"kId = %@",[NSString stringWithFormat:@"%lld",khEntity.kId]];
    request.predicate = predic;

    //请求数据
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:nil];
    KeHuEntity *kh = [objs firstObject];
    kh.address = khEntity.address;
    kh.beizhu = khEntity.beizhu;
    kh.name = khEntity.name;
    kh.phone = khEntity.phone;
    kh.time = khEntity.time;
    kh.pinyin = khEntity.pinyin;
    
    NSError* erro = nil;

    if (![self.managedObjectContext save:&erro]) {
        
        NSLog(@"更新失败-->>%@",erro);
        return NO;
        
    }
    else
    {
        return YES;
    }
}

//查询客户
-(NSMutableArray<KeHuEntity*>*)selectKeHu
{
    //以上代码简写成下边
    NSFetchRequest *request = [KeHuEntity fetchRequest];
    
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"zhang"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*zhang*)
    // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*zhang*"];
    // request.predicate = predicate;
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* keHuArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return keHuArry;
}

//获取kid
-(NSString*)getKid
{
    NSString* kId = [[NSUserDefaults standardUserDefaults] objectForKey:@"kId"];
    NSInteger kIdInt = [kId integerValue];
    ++kIdInt;
    
    NSString* addKid = [NSString stringWithFormat:@"%ld",kIdInt];
    [[NSUserDefaults standardUserDefaults] setObject:addKid forKey:@"kId"];
    
    return addKid;
}

//创建客户
-(KeHuModel*)createKeHuModel
{
    return [[KeHuModel alloc] init];
}

//转实体
-(KeHuModel*)toKeHuModel:(KeHuEntity*)spEntity;
{
    KeHuModel* model    = [[KeHuModel alloc] init];
    model.address       = spEntity.address;
    model.beizhu        = spEntity.beizhu;
    model.kId           = spEntity.kId;
    model.name          = spEntity.name;
    model.phone         = spEntity.phone;
    model.time          = spEntity.time;
    return model;
}

//转实体
-(KeHuEntity*)toKeHuEntity:(KeHuModel*)model
{
    KeHuEntity* entity    = [self createKeHuEntity];
    entity.address       = model.address;
    entity.beizhu        = model.beizhu;
    entity.kId           = model.kId;
    entity.name          = model.name;
    entity.phone         = model.phone;
    entity.time          = model.time;
    return entity;
}

//创建商品
-(ShangPinEntity*)createShangPinEntity
{
    return [NSEntityDescription insertNewObjectForEntityForName:@"ShangPinEntity" inManagedObjectContext:self.managedObjectContext];
}

//插入商品
-(BOOL)insertShangPin:(ShangPinEntity*)spEntity
{
    spEntity.time = [NSDate date];
    spEntity.sId = [[self getSid] integerValue];
    NSError* erro = nil;
    
    if (![self.managedObjectContext save:&erro]) {
        
        NSLog(@"保存失败-->>%@",erro);
        
        return NO;
        
    }
    else
    {
        return YES;
    }
}

//删除商品
-(BOOL)deleteShangPin:(ShangPinEntity*)spEntity
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ShangPinEntity"];
    
    //查到到你要删除的数据库中的对象
    NSPredicate *predic = [NSPredicate predicateWithFormat:@"sId = %@",[NSString stringWithFormat:@"%lld",spEntity.sId]];
    request.predicate = predic;
    
    //请求数据
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:nil];
    
    for (ShangPinEntity *sp in objs) {
        
        [self.managedObjectContext deleteObject:sp];
        
        [[CoreDataManager shareManager] updateShangPinFenLeiId:[sp.fId stringValue] kunCunCount:-(sp.kucun)];

    }
    
    if ([self.managedObjectContext save:nil]) {
        
        
        return YES;
    }
    else
    {
        return NO;
    }
    
}

//更新商品
-(BOOL)updateShangPin:(ShangPinEntity*)spEntity
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ShangPinEntity"];
    //查到到你要删除的数据库中的对象
    NSPredicate *predic = [NSPredicate predicateWithFormat:@"sId = %@",[NSString stringWithFormat:@"%lld",spEntity.sId]];
    request.predicate = predic;
    
    //请求数据
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:nil];
    ShangPinEntity *sp = [objs firstObject];
    
    sp.buyCount = spEntity.buyCount;
    sp.chenben = spEntity.chenben;
    sp.danjia = spEntity.danjia;
    sp.fId = spEntity.fId;
    sp.flName = spEntity.flName;
    sp.kucun = spEntity.kucun;
    sp.name = spEntity.name;
    sp.time = spEntity.time;
    sp.pinyin = spEntity.pinyin;

    NSError* erro = nil;
    
    if (![self.managedObjectContext save:&erro]) {
        
        NSLog(@"更新失败-->>%@",erro);
        return NO;
    }
    else
    {
        return YES;
    }
}

//查询商品
-(NSMutableArray<ShangPinEntity*>*)selectShangPin
{
    //以上代码简写成下边
    NSFetchRequest *request = [ShangPinEntity fetchRequest];
    
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"zhang"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*zhang*)
    // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*zhang*"];
    // request.predicate = predicate;
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
    
}

//查询商品
-(NSMutableArray<ShangPinEntity*>*)selectShangPinWithFlId:(NSInteger)flId
{
    //以上代码简写成下边
    NSFetchRequest *request = [ShangPinEntity fetchRequest];
    
    // 设置条件过滤(搜索name中包含字符串"zhang"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*zhang*)
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fId = %ld", flId];
     request.predicate = predicate;
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
    
}

//查询商品
-(NSMutableArray<ShangPinEntity*>*)selectShangPinWithIds:(NSString*)ids
{
    NSMutableArray* idsArry = [NSMutableArray array];
    
    for (NSString* str in [ids componentsSeparatedByString:@","]) {
        
        [idsArry addObject:[NSString stringWithFormat:@"%@",str]];
    }
    
    NSString* string = [NSString stringWithFormat:@"sId IN { %@ }",[idsArry componentsJoinedByString:@","]];
    
    //以上代码简写成下边
    NSFetchRequest *request = [ShangPinEntity fetchRequest];
    NSPredicate* predicate = [NSPredicate predicateWithFormat:string];
    request.predicate = predicate;
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
}

//创建商品
-(ShangPinModel*)createShangPinModel
{
    ShangPinModel* model = [[ShangPinModel alloc] init];
    return model;
}

//商品实体
-(ShangPinEntity*)toShangPinEntity:(ShangPinModel*)model
{
    ShangPinEntity* entity = [self createShangPinEntity];

    entity.chenben = model.chenben;
    entity.danjia = model.danjia;
    entity.fId = model.fId;
    entity.flName = model.flName;
    entity.kucun = model.kucun;
    entity.name = model.name;
    entity.sId = model.sId;
    entity.time = model.time;
    entity.buyCount = model.buyCount;
    
    return entity;
}

//更新库存
-(BOOL)updateShangPinId:(NSString*)sId kunCunCount:(NSInteger)count
{
    NSMutableArray* flEntityArry = [self selectShangPinWithIds:sId];
    ShangPinEntity* entity = [flEntityArry firstObject];
    NSInteger kuCunInt = entity.kucun;
    kuCunInt += count;
    entity.kucun = kuCunInt;
    
    if ([self.managedObjectContext save:nil]) {
        
        return YES;
    }
    else
    {
        return NO;
    }
    
}

//获取sid
-(NSString*)getSid
{
    NSString* kId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sId"];
    NSInteger kIdInt = [kId integerValue];
    ++kIdInt;
    
    NSString* addKid = [NSString stringWithFormat:@"%ld",kIdInt];
    [[NSUserDefaults standardUserDefaults] setObject:addKid forKey:@"sId"];
    
    return addKid;
    
}


//创建商品分类
-(ShangPinFenLeiEntity*)createShangPinFenLeiEntity
{
    return [NSEntityDescription insertNewObjectForEntityForName:@"ShangPinFenLeiEntity" inManagedObjectContext:self.managedObjectContext];
}

//插入商品分类
-(BOOL)insertShangPinFenLei:(ShangPinFenLeiEntity*)spEntity
{
    spEntity.time = [NSDate date];
    spEntity.fId = [[self getFid] integerValue];
    NSError* erro = nil;
    
    if (![self.managedObjectContext save:&erro]) {
        
        NSLog(@"保存失败-->>%@",erro);
        
        return NO;
        
    }
    else
    {
        return YES;
    }
    
}

//删除商品分类
-(BOOL)deleteShangPinFenLei:(ShangPinFenLeiEntity*)spEntity
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ShangPinFenLeiEntity"];
    
    //查到到你要删除的数据库中的对象
    NSPredicate *predic = [NSPredicate predicateWithFormat:@"fId = %@",[NSString stringWithFormat:@"%lld",spEntity.fId]];
    request.predicate = predic;
    
    //请求数据
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:nil];
    
    for (ShangPinEntity *sp in objs) {
        
        [self.managedObjectContext deleteObject:sp];
    }
    
    if ([self.managedObjectContext save:nil]) {
        
        return YES;
    }
    else
    {
        return NO;
    }
    
}

//更新商品分类
-(BOOL)updateShangPinFenLei:(ShangPinFenLeiEntity*)spEntity
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ShangPinFenLeiEntity"];
    //查到到你要删除的数据库中的对象
    NSPredicate *predic = [NSPredicate predicateWithFormat:@"fId = %@",[NSString stringWithFormat:@"%lld",spEntity.fId]];
    request.predicate = predic;
    
    //请求数据
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:nil];
    ShangPinFenLeiEntity *sp = [objs firstObject];
    
    sp.fId = spEntity.fId;
    sp.kucunCount = spEntity.kucunCount;
    sp.name = spEntity.name;
    sp.fId = spEntity.fId;
    sp.saleCount = spEntity.saleCount;
    sp.time = spEntity.time;
    sp.pinyin = spEntity.pinyin;
    
    NSError* erro = nil;
    
    if (![self.managedObjectContext save:&erro]) {
        
        NSLog(@"更新失败-->>%@",erro);
        return NO;
    }
    else
    {
        return YES;
    }
}

//更新库存
-(BOOL)updateShangPinFenLeiId:(NSString*)fId kunCunCount:(NSInteger)count
{
    NSMutableArray* flEntityArry = [self selectShangPinFenLeiWithFid:fId];
    
    ShangPinFenLeiEntity* flEntity = [flEntityArry firstObject];
    
    NSInteger kuCunInt = [flEntity.kucunCount integerValue];
    kuCunInt += count;
    flEntity.kucunCount = @(kuCunInt);
    
    NSInteger saleCount = [flEntity.saleCount integerValue];
    saleCount -= count;
    flEntity.saleCount = @(saleCount);

    if ([self.managedObjectContext save:nil]) {
        
        return YES;
    }
    else
    {
        return NO;
    }

}

//查询商品分类Id
-(NSMutableArray<ShangPinFenLeiEntity*>*)selectShangPinFenLeiWithFid:(NSString*)fId
{
    //以上代码简写成下边
    NSFetchRequest *request = [ShangPinFenLeiEntity fetchRequest];
    
    // 设置排序（按照age降序）
    // 设置条件过滤(搜索name中包含字符串"zhang"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*zhang*)
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fId = %@", fId];
     request.predicate = predicate;
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
}

//查询商品分类
-(NSMutableArray<ShangPinFenLeiEntity*>*)selectShangPinFenLei
{
    //以上代码简写成下边
    NSFetchRequest *request = [ShangPinFenLeiEntity fetchRequest];
    
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"zhang"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*zhang*)
    // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*zhang*"];
    // request.predicate = predicate;
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
}

//查询今日商品分类 销售排行
-(NSMutableArray<ShangPinFenLeiModel*>*)selectSaleMoreWithToday
{
    
    NSMutableArray* flArry = [self selectShangPinFenLei];
    NSMutableArray* flModelArry = [[NSMutableArray alloc] init];
    
    for (ShangPinFenLeiEntity* flEntity in flArry) {
        
        //以上代码简写成下边
        NSFetchRequest *request = [ZhangDanShangPinRelationEntity fetchRequest];
        
        // 设置排序（按照age降序）
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"fId" ascending:NO];
        request.sortDescriptors = [NSArray arrayWithObject:sort];
        
        NSTimeInterval startTime = [TimeTool getTodayStartDay];
        NSDate* beginDate = [NSDate dateWithTimeIntervalSince1970:startTime];
        NSDate* endDate = [NSDate dateWithTimeIntervalSince1970:[TimeTool getTodayEndDayWithStartDay:startTime] -1];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"time >= %@ AND time <= %@ AND fId = %lld",beginDate,endDate,flEntity.fId];
        request.predicate = predicate;
        
        // 执行请求
        NSError *error = nil;
        NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
        if (error) {
            [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
        }
        
        NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
        
        NSInteger saleCount = 0;
        
        for (ZhangDanShangPinRelationEntity* entity in shangPinArry) {
            
            saleCount += entity.shuliang;
            
        }

        ShangPinFenLeiModel* model = [self toShangPinFenLeiModel:flEntity];
        model.saleCount = @(saleCount);
        [flModelArry addObject:model];
    }
    
    return flModelArry;
}

//查询本周商品分类 销售排行
-(NSMutableArray<ShangPinFenLeiModel*>*)selectSaleMoreWithWeek
{
    
    NSMutableArray* flArry = [self selectShangPinFenLei];
    NSMutableArray* flModelArry = [[NSMutableArray alloc] init];
    
    for (ShangPinFenLeiEntity* flEntity in flArry) {
        
        //以上代码简写成下边
        NSFetchRequest *request = [ZhangDanShangPinRelationEntity fetchRequest];
        
        // 设置排序（按照age降序）
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"fId" ascending:NO];
        request.sortDescriptors = [NSArray arrayWithObject:sort];
        
    
        NSString* beginAndEndString = [TimeTool getWeekTime];
        NSArray* timeArry = [beginAndEndString componentsSeparatedByString:@"-"];
        NSDate* beginDate = [NSDate dateWithTimeIntervalSince1970:[[timeArry firstObject] doubleValue]];
        NSDate* endDate = [NSDate dateWithTimeIntervalSince1970:[[timeArry lastObject] doubleValue]];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"time >= %@ AND time <= %@ AND fId = %lld",beginDate,endDate,flEntity.fId];
        request.predicate = predicate;

        
        // 执行请求
        NSError *error = nil;
        NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
        if (error) {
            [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
        }
        
        NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
        
        NSInteger saleCount = 0;
        
        for (ZhangDanShangPinRelationEntity* entity in shangPinArry) {
            
            saleCount += entity.shuliang;
            
        }
        
        ShangPinFenLeiModel* model = [self toShangPinFenLeiModel:flEntity];
        model.saleCount = @(saleCount);
        [flModelArry addObject:model];
    }
    
    return flModelArry;

}

//查询本周商品分类 销售排行
-(NSMutableArray<ShangPinFenLeiModel*>*)selectSaleMoreWithMonth
{
    
    NSMutableArray* flArry = [self selectShangPinFenLei];
    NSMutableArray* flModelArry = [[NSMutableArray alloc] init];
    
    for (ShangPinFenLeiEntity* flEntity in flArry) {
        
        //以上代码简写成下边
        NSFetchRequest *request = [ZhangDanShangPinRelationEntity fetchRequest];
        
        // 设置排序（按照age降序）
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"fId" ascending:NO];
        request.sortDescriptors = [NSArray arrayWithObject:sort];
        
        NSTimeInterval startTime = [TimeTool getFirstDayOfMonth:[NSDate date].timeIntervalSince1970];
        NSDate* beginDate = [NSDate dateWithTimeIntervalSince1970:startTime];
        NSDate* endDate = [NSDate dateWithTimeIntervalSince1970:[TimeTool getFirstDayOfNextMonth:startTime] -1];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"time >= %@ AND time <= %@ AND fId = %lld",beginDate,endDate,flEntity.fId];
        request.predicate = predicate;
        
        
        // 执行请求
        NSError *error = nil;
        NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
        if (error) {
            [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
        }
        
        NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
        
        NSInteger saleCount = 0;
        
        for (ZhangDanShangPinRelationEntity* entity in shangPinArry) {
            
            saleCount += entity.shuliang;
            
        }
        
        ShangPinFenLeiModel* model = [self toShangPinFenLeiModel:flEntity];
        model.saleCount = @(saleCount);
        [flModelArry addObject:model];
    }
    
    return flModelArry;
    
}



//查询本周商品分类 销售排行
-(NSMutableArray<ShangPinFenLeiModel*>*)selectSaleMoreWithYear
{
    
    NSMutableArray* flArry = [self selectShangPinFenLei];
    NSMutableArray* flModelArry = [[NSMutableArray alloc] init];
    
    for (ShangPinFenLeiEntity* flEntity in flArry) {
        
        //以上代码简写成下边
        NSFetchRequest *request = [ZhangDanShangPinRelationEntity fetchRequest];
        
        // 设置排序（按照age降序）
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"fId" ascending:NO];
        request.sortDescriptors = [NSArray arrayWithObject:sort];
        
        NSTimeInterval startTime = [TimeTool getFirstDayOfYear];
        NSDate* beginDate = [NSDate dateWithTimeIntervalSince1970:startTime];
        NSDate* endDate = [NSDate dateWithTimeIntervalSince1970:[TimeTool getFirstDayOfNextYear] -1];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"time >= %@ AND time <= %@ AND fId = %lld",beginDate,endDate,flEntity.fId];
        request.predicate = predicate;
        
        
        // 执行请求
        NSError *error = nil;
        NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
        if (error) {
            [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
        }
        
        NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
        
        NSInteger saleCount = 0;
        
        for (ZhangDanShangPinRelationEntity* entity in shangPinArry) {
            
            saleCount += entity.shuliang;
            
        }
        
        ShangPinFenLeiModel* model = [self toShangPinFenLeiModel:flEntity];
        model.saleCount = @(saleCount);
        [flModelArry addObject:model];
    }
    
    return flModelArry;
    
}


//查询本周商品分类 库存排行
-(NSMutableArray<ShangPinFenLeiEntity*>*)selectKunCunWithToday
{
    //以上代码简写成下边
    NSFetchRequest *request = [ShangPinFenLeiEntity fetchRequest];
    
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"kucunCount" ascending:YES];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
}

//转换对象
-(ShangPinFenLeiModel*)toShangPinFenLeiModel:(ShangPinFenLeiEntity*)spEntity
{
    ShangPinFenLeiModel* model = [[ShangPinFenLeiModel alloc] init];
    model.fId = spEntity.fId;
    model.name = spEntity.name;
    model.time = spEntity.time;
    model.saleCount = spEntity.saleCount;
    model.kucunCount = spEntity.kucunCount;
    return model;
}

//创建商品
-(ShangPinFenLeiModel*)createShangPinFenLeiModel
{
    return [[ShangPinFenLeiModel alloc] init];
}

//商品实体
-(ShangPinFenLeiEntity*)toShangPinFenLeiEntity:(ShangPinFenLeiModel*)model
{
    ShangPinFenLeiEntity* entity = [self createShangPinFenLeiEntity];
    entity.fId = model.fId;
    entity.name = model.name;
    entity.time = model.time;
    entity.saleCount = model.saleCount;
    entity.kucunCount = model.kucunCount;
    return entity;
}


//获取Fid
-(NSString*)getFid
{
    NSString* kId = [[NSUserDefaults standardUserDefaults] objectForKey:@"fId"];
    NSInteger kIdInt = [kId integerValue];
    ++kIdInt;
    
    NSString* addKid = [NSString stringWithFormat:@"%ld",kIdInt];
    [[NSUserDefaults standardUserDefaults] setObject:addKid forKey:@"fId"];
    
    return addKid;
    
}


//创建账单
-(ZhangDanEntity*)createZhangDanEntity
{
    return [NSEntityDescription insertNewObjectForEntityForName:@"ZhangDanEntity" inManagedObjectContext:self.managedObjectContext];
}

//插入账单
-(BOOL)insertZhangDan:(ZhangDanEntity*)zdEntity isHaveIds:(BOOL)isHaveIdsBool
{
    zdEntity.time = [NSDate date];
    
    if(!isHaveIdsBool)
    {
        zdEntity.zId= [[self getZid] integerValue];
    }
    
    NSError* erro = nil;
    
    if (![self.managedObjectContext save:&erro]) {
        
        NSLog(@"保存失败-->>%@",erro);
        
        return NO;
        
    }
    else
    {
        return YES;
    }
    
}

//删除账单
-(BOOL)deleteZhangDan:(ZhangDanEntity*)zdEntity
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ZhangDanEntity"];
    
    //查到到你要删除的数据库中的对象
    NSPredicate *predic = [NSPredicate predicateWithFormat:@"zId = %@",[NSString stringWithFormat:@"%lld",zdEntity.zId]];
    request.predicate = predic;
    
    //请求数据
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:nil];
    
    for (ZhangDanEntity *zdEntity in objs) {
        
        [self.managedObjectContext deleteObject:zdEntity];
        
        NSMutableArray* zdsprArry = [self selectZhangDanShangPinRelationWithIds:zdEntity.zdsprIds];
        
        for (ZhangDanShangPinRelationEntity* entity in zdsprArry) {
            
            [self updateShangPinFenLeiId:[entity.fId stringValue] kunCunCount:entity.shuliang];
            [self updateShangPinId:[NSString stringWithFormat:@"%lld",entity.spId] kunCunCount:entity.shuliang];
            [self deleteZhangDanShangPinRelation:entity];
        }
        
    }
    
    if ([self.managedObjectContext save:nil]) {
        
        return YES;
    }
    else
    {
        return NO;
    }
}

//更新账单
-(BOOL)updateZhangDanIsPayWithZid:(NSInteger)zId
{
    NSMutableArray* zdArry = [self selectZhangDanWithZid:zId];
    
    ZhangDanEntity* entity = [zdArry firstObject];
    entity.isPay = [NSNumber numberWithInt:1];
    
    if ([self.managedObjectContext save:nil]) {
        
        return YES;
    }
    else
    {
        return NO;
    }

    return YES;
}

//查询账单
-(NSMutableArray<ZhangDanEntity*>*)selectZhangDan
{
    //以上代码简写成下边
    NSFetchRequest *request = [ZhangDanEntity fetchRequest];
    
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"zhang"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*zhang*)
    // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*zhang*"];
    // request.predicate = predicate;
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
    
}

//查询账单
-(NSMutableArray<ZhangDanEntity*>*)selectZhangDanWithZid:(NSInteger)zid
{
    //以上代码简写成下边
    NSFetchRequest *request = [ZhangDanEntity fetchRequest];
    
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 设置条件过滤(搜索name中包含字符串"zhang"的记录，注意：设置条件过滤时，数据库SQL语句中的%要用*来代替，所以%Itcast-1%应该写成*zhang*)
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"zId = %lld", zid];
     request.predicate = predicate;
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
    
}

//查询今日商品分类 销售排行
-(NSMutableArray<ZhangDanEntity*>*)selectZhangDanWithToday
{
    //以上代码简写成下边
    NSFetchRequest *request = [ZhangDanEntity fetchRequest];
    
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    
    NSDate* beginDate = [NSDate dateWithTimeIntervalSince1970:[TimeTool getTodayStartDay]];
    NSDate* endDate = [NSDate dateWithTimeIntervalSince1970:[TimeTool getTodayEndDayWithStartDay:beginDate.timeIntervalSince1970]];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"time >= %@ AND time <= %@",beginDate,endDate];
    request.predicate = predicate;


    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
    
}


-(NSMutableArray<ZhangDanEntity*>*)selectZhangDanWithWeek
{
    //以上代码简写成下边
    NSFetchRequest *request = [ZhangDanEntity fetchRequest];
    
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];

    
    NSString* beginAndEndString = [TimeTool getWeekTime];
    NSArray* timeArry = [beginAndEndString componentsSeparatedByString:@"-"];
    NSDate* beginDate = [NSDate dateWithTimeIntervalSince1970:[[timeArry firstObject] doubleValue]];
    NSDate* endDate = [NSDate dateWithTimeIntervalSince1970:[[timeArry lastObject] doubleValue]];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"time >= %@ AND time <= %@",beginDate,endDate];
    request.predicate = predicate;

    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
    
}
//查询本周商品分类 销售排行
-(NSMutableArray<ZhangDanEntity*>*)selectZhangDanWithMonth
{
    //以上代码简写成下边
    NSFetchRequest *request = [ZhangDanEntity fetchRequest];
    
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];

    NSDate* beginDate = [NSDate dateWithTimeIntervalSince1970:[TimeTool getFirstDayOfMonth:[NSDate date].timeIntervalSince1970]];
    NSDate* endDate = [NSDate dateWithTimeIntervalSince1970:[TimeTool getFirstDayOfNextMonth:beginDate.timeIntervalSince1970] -1];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"time >= %@ AND time <= %@",beginDate,endDate];
    request.predicate = predicate;

    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
    
}
//查询本周商品分类 销售排行
-(NSMutableArray<ZhangDanEntity*>*)selectZhangDanWithYear
{
    //以上代码简写成下边
    NSFetchRequest *request = [ZhangDanEntity fetchRequest];
    
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    
    
    NSDate* beginDate = [NSDate dateWithTimeIntervalSince1970:[TimeTool getFirstDayOfYear]];
    NSDate* endDate = [NSDate dateWithTimeIntervalSince1970:[TimeTool getFirstDayOfNextYear] -1];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"time >= %@ AND time <= %@",beginDate,endDate];
    request.predicate = predicate;

    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
    
}

//查询本周商品分类 销售排行
-(NSMutableArray<ZhangDanEntity*>*)selectQianKuanZhangDan
{
    //以上代码简写成下边
    NSFetchRequest *request = [ZhangDanEntity fetchRequest];
    
    // 设置排序（按照age降序）
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"payType = 3 AND isPay = 0"];
    request.predicate = predicate;
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
    
}

//获取Zid
-(NSString*)getZid
{
    NSString* kId = [[NSUserDefaults standardUserDefaults] objectForKey:@"zId"];
    NSInteger kIdInt = [kId integerValue];
    ++kIdInt;
    
    NSString* addKid = [NSString stringWithFormat:@"%ld",kIdInt];
    [[NSUserDefaults standardUserDefaults] setObject:addKid forKey:@"zId"];
    
    return addKid;
    
}

//账单实体
-(ZhangDanModel*)toZhangDanModel:(ZhangDanEntity*)entity
{
    ZhangDanModel* model = [[ZhangDanModel alloc] init];
    model.chenben = entity.chenben;
    model.lirun = entity.lirun;
    model.name = entity.name;
    model.payType = entity.payType;
    model.time = entity.time;
    model.zdsprIds = entity.zdsprIds;
    model.zId = entity.zId;
    model.zongjia = entity.zongjia;
    model.kId = entity.kId;
    model.kehuName = entity.kehuName;
    model.kehuPhone = entity.kehuPhone;

    return model;
}

//账单实体
-(ZhangDanEntity*)toZhangDanEntity:(ZhangDanModel*)model
{
    ZhangDanEntity* entity = [self createZhangDanEntity];
    entity.chenben = model.chenben;
    entity.lirun = model.lirun;
    entity.name = model.name;
    entity.payType = model.payType;
    entity.time = model.time;
    entity.zdsprIds = model.zdsprIds;
    entity.zId = model.zId;
    entity.zongjia = model.zongjia;
    entity.kId = model.kId;
    entity.kehuName = model.kehuName;
    entity.kehuPhone = model.kehuPhone;

    return entity;
}

//创建实体
-(ZhangDanModel*)createZhangDanModel
{
    ZhangDanModel* model = [[ZhangDanModel alloc] init];
    return model;
}

//创建账单和商品的关联表
-(ZhangDanShangPinRelationEntity*)createZhangDanShangPinRelationEntity
{
    return [NSEntityDescription insertNewObjectForEntityForName:@"ZhangDanShangPinRelationEntity" inManagedObjectContext:self.managedObjectContext];
    
}

//插入关联表
-(BOOL)insertZhangDanShangPinRelation:(ZhangDanShangPinRelationEntity*)glEntity isHaveIds:(BOOL)isHaveIdsBool
{
    if (!isHaveIdsBool) {
    
        glEntity.zdsprId = [[self getZdsprId] integerValue];
    }
    
    glEntity.time = [NSDate date];

    NSError* erro = nil;
    
    if (![self.managedObjectContext save:&erro]) {
        
        NSLog(@"保存失败-->>%@",erro);
        
        return NO;
        
    }
    else
    {
        return YES;
    }
    
}

//删除关联表
-(BOOL)deleteZhangDanShangPinRelation:(ZhangDanShangPinRelationEntity*)glEntity
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"ZhangDanShangPinRelationEntity"];
    
    //查到到你要删除的数据库中的对象
    NSPredicate *predic = [NSPredicate predicateWithFormat:@"zdsprId = %@",[NSString stringWithFormat:@"%lld",glEntity.zdsprId]];
    request.predicate = predic;
    
    //请求数据
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:nil];
    
    for (ShangPinEntity *sp in objs) {
        
        [self.managedObjectContext deleteObject:sp];
    }
    
    if ([self.managedObjectContext save:nil]) {
        
        return YES;
    }
    else
    {
        return NO;
    }
    
}

//更新关联表
-(BOOL)updateZhangDanShangPinRelation:(ZhangDanShangPinRelationEntity*)glEntity
{
    return YES;
}

//查询关联表
-(NSMutableArray<ZhangDanShangPinRelationEntity*>*)selectZhangDanShangPinRelation
{
    //以上代码简写成下边
    NSFetchRequest *request = [ZhangDanShangPinRelationEntity fetchRequest];
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
    
}

//查询关联表
-(NSMutableArray<ZhangDanShangPinRelationEntity*>*)selectZhangDanShangPinRelationWithIds:(NSString*)ids
{
    NSMutableArray* idsArry = [NSMutableArray array];
    
    for (NSString* str in [ids componentsSeparatedByString:@","]) {
        
        [idsArry addObject:[NSString stringWithFormat:@"%@",str]];
    }
    
    //以上代码简写成下边
    NSFetchRequest *request = [ZhangDanShangPinRelationEntity fetchRequest];
    
    NSString* zdsprIdString = [NSString stringWithFormat:@"zdsprId IN { %@ }",[idsArry componentsJoinedByString:@","]];
    
    NSPredicate* predicate = [NSPredicate predicateWithFormat:zdsprIdString];
    request.predicate = predicate;
    
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    NSMutableArray* shangPinArry = [[NSMutableArray alloc] initWithArray:objs];
    
    return shangPinArry;
    
}
-(NSString*)getZdsprId
{
    NSString* kId = [[NSUserDefaults standardUserDefaults] objectForKey:@"zdsprId"];
    NSInteger kIdInt = [kId integerValue];
    ++kIdInt;
    
    NSString* addKid = [NSString stringWithFormat:@"%ld",kIdInt];
    [[NSUserDefaults standardUserDefaults] setObject:addKid forKey:@"zdsprId"];
    
    return addKid;
}

//获取账单和商品的关联id
-(void)setZdsprId:(NSInteger)zdsprId
{
    NSString* addKid = [NSString stringWithFormat:@"%ld",zdsprId];
    [[NSUserDefaults standardUserDefaults] setObject:addKid forKey:@"zdsprId"];

}

-(ZhangDanShangPinRelationModel*)toZhangDanShangPinRelationModel:(ZhangDanShangPinRelationEntity*)entity
{
    ZhangDanShangPinRelationModel* model = [[ZhangDanShangPinRelationModel alloc] init];
    model.shuliang = entity.shuliang;
    model.spId = entity.spId;
    model.zdId = entity.zdId;
    model.zdsprId = entity.zdsprId;
    model.time = entity.time;
    model.fId = entity.fId;
    return model;
}

//账单实体
-(ZhangDanShangPinRelationEntity*)toZhangDanShangPinRelationEntity:(ZhangDanShangPinRelationModel*)model
{
    ZhangDanShangPinRelationEntity* entity = [self createZhangDanShangPinRelationEntity];
    entity.shuliang = model.shuliang;
    entity.spId = model.spId;
    entity.zdId = model.zdId;
    entity.zdsprId = model.zdsprId;
    entity.time = model.time;
    entity.fId = model.fId;
    
    return entity;

}

//创建实体
-(ZhangDanShangPinRelationModel*)createZhangDanShangPinRelationModel
{
    return [[ZhangDanShangPinRelationModel alloc] init];
}


@end
